const eventHandler = function (eid) {
    console.log(eid);
    handleEventQueue(eid);
    if (eid == 3) {
        // 退出当前小地图
        clearAreaScreen();
        return;
    }
    // 根据 area id 处理不同的事件，用回调函数，弹出选项，让玩家决定
    // 再根据势力决定某些行为结果
    const renderAreaScreen = (buttons) => {
        let _t = document.querySelector('.areaScreen');
        _t.innerText = '';
        _t.style.display = 'flex';
        let _f = document.createDocumentFragment();
        for (let i = 0; i < buttons.length; i++) {
            let btn = document.createElement(buttons[i].type);
            if (buttons[i].type == 'div') {
                btn.dataset.id = [...(buttons[i].id)];
                let names = buttons[i].id[0] == 'item' ? itemNames : monsterNames;
                btn.style.backgroundImage = `url(icon/${buttons[i].id[0]}/${names[buttons[i].id[1]]}.png)`;
            } else if (buttons[i].type == 'button') {
                if (buttons[i].id != undefined) {
                    btn.dataset.id = buttons[i].id;
                }
                btn.innerText = buttons[i].name;
            }
            btn.addEventListener('click', handleClickArea, { once: true })
            _f.append(btn)
        }
        _t.append(_f);
    }
    let btns = areaData[eid].func(eid)
    if (typeof btns == 'object') {
        renderAreaScreen(btns)
    }
}
let areaMapPos = -1;
let mapBak = '';
function handleClickAreaMap(e) {
    console.log("小地图", e.target.dataset.id);
    if (e.target.previousElementSibling) {
        removeClass(e.target.previousElementSibling, 'curpos');
    }
    addClass(e.target, 'gone');
    addClass(e.target, 'curpos');
    removeClass(e.target, "hints");
    if (e.target.nextElementSibling) {
        addClass(e.target.nextElementSibling, "hints");
    }
    let _tmp = e.target.dataset.id.split(',')
    let type = _tmp[0]
    let id = _tmp[1]
    areaMapPos++;
    // 处理点击区域屏幕的小地图块
    if (type == 1 && id == 3) {
        areaMapPos = -1;
        mapBak = '';
        // 点击了出口，离开areaScreen
        eventHandler(id);
        return;
    }
    if (type == 0) {
        e.target.nextElementSibling.addEventListener('click', handleClickAreaMap, { once: true });
        // 点击了怪物
        battleHandler(id);
        return;
    }
    if (id != 3) {
        // 如果是港口、营地，先保持当前小地图
        mapBak = document.querySelector('.areaScreen').innerHTML;
        eventHandler(id);
    }
}
function exitArea() {
    // 离开对话
    if (mapBak != '') {
        // 回归小地图
        document.querySelector('.areaScreen').innerHTML = mapBak;
        document.querySelector('.areaScreen').children[areaMapPos + 1].addEventListener('click', handleClickAreaMap, { once: true });
    } else {
        // 隐藏区域对话界面
        clearAreaScreen()
    }
}
function handleClickArea(e) {
    console.log(e);
    let _name = e.target.innerText
    let _id = e.target.dataset.id
    switch (_name) {
        case '无视':
        case '离开':
            exitArea()
            break;
        case '进入':
            if (_id) {
                console.log(_id);
            }
            // 清除对话选项
            let _sc = document.querySelector('.areaScreen');
            _sc.innerText = '';
            // 生成小地图并渲染
            let _t = document.createDocumentFragment()
            let _newmap = game.genMap(4);
            // 解析地图
            for (let i = 0; i < _newmap.length; i++) {
                let _map = document.createElement('div')
                let type = _newmap[i][0];
                let id = _newmap[i][1];
                _map.dataset.id = _newmap[i];
                _map.style.opacity = 0;
                if (type == 0) {
                    // 渲染怪物
                    _map.style.backgroundImage = `url(icon/monster/${monsterNames[id]}.png)`;
                } else {
                    // 渲染房间
                    _map.style.backgroundImage = `url(icon/area/${areaNames[id]}.png)`;
                }
                _t.append(_map);
            }
            // 允许点击第一个怪物
            addClass(_t.firstElementChild, "hints");
            _t.firstElementChild.addEventListener("click", handleClickAreaMap, { once: true });
            _sc.append(_t)
            break;
        case '锻炼':
            heroTrain()
            exitArea()
            break;
        case '休息':
            heroRest()
            exitArea()
            break;
        case '战斗':
            console.log("触发守卫战斗");
            battleHandler(_id);
            exitArea()
            break;
        case '交谈':
            console.log("交谈");
            talkToGuard(_id);
            exitArea()
            break;
        case '传送':
            heroTransport();
            exitArea()
            break;
        case '祈祷':
            console.log("祈祷");
            heroPray()
            exitArea()
            break;
        case '破坏':
            console.log("破坏");
            game.hero.heroInfo.abilities[2] += getRandomRange(1, 10);
            renderHeroStat();
            exitArea()
            break;
        case '复活':
            console.log("复活");
            game.hero.getPet(game.hero.petInfo.lastDeadPet);
            exitArea()
            break;
        case '拔出':
            console.log("拔出");
            game.hero.getItem(getRandomRange(0, 16));
            exitArea()
            break;
        case '强化':
            console.log("学会了新技能");
            game.hero.learnMove();
            exitArea()
            break;
        case '探索':
            console.log("探索");
            talkToGuard(_id);
            exitArea()
            break;
        case '躲避':
            console.log("躲避");
            heroStayAway(_id)
            exitArea()
            break;
        case '停留':
            console.log("停留");
            heroStay(_id)
            exitArea()
            break;
        case '修整':
            console.log("修整");
            heroTrain();
            exitArea()
            break;
        default:
            let id = (e.target.dataset.id).split(',');
            console.log(id);
            if (id[0] == 'item') {
                // 点击了购买物品
                if (id[2] == 'exp' && game.hero.heroInfo.exp[0] >= id[3]) {
                    game.hero.heroInfo.exp[0] -= id[3];
                    renderHeroBar()
                    game.hero.getItem(id[1]);
                    addClass(e.target, 'unactive');
                }
            } else if (id[0] == 'monster') {
                // 点击了购买宠物
                if (id[2] == 'exp' && game.hero.heroInfo.exp[0] >= id[3]) {
                    game.hero.heroInfo.exp[0] -= id[3];
                    renderHeroBar()
                    game.hero.getPet(id[1]);
                    addClass(e.target, 'unactive');
                }
            } else if (!id) {
                // 点击了其他按钮，继续解析
                if (0) {

                }
            }
            break;
    }
}
let eventQueue = [];
const handleEventQueue = function (_i) {
    // 处理战斗队列,有无战前先生效的函数
    for (let i = 0; i < eventQueue.length; i++) {
        if (typeof eventQueue[i] == 'function') {
            // 如果处理结果是 true 说明已处理完了，移出队列
            if (eventQueue[i](_i)) {
                console.log("已处理", i);
                eventQueue.splice(i, 1);
            } else {
                console.log("继续等待，未处理", i);
            }
        }
    }
}